package io.jee.medusa.remote;

import io.jee.runshan.utils.JsonUtil;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class RemoteConnector {
	private static final Logger logger = LoggerFactory.getLogger(RemoteConnector.class);
	
	public static <T> T post(String actionUrl, String params, Class<T> clz) {
		T response = null;
		try {
	        String json = send(actionUrl, params, "POST");
	        if (clz != null) {
	        	response = JsonUtil.jsonToBean(json, clz);
	        }
		} catch (Exception e) {
			e.printStackTrace();
		}
        return response;
	}
	
	public static <T> T get(String actionUrl, String params, Class<T> clz) {
		T response = null;
		try {
	        String json = send(actionUrl, params, "GET");
	        if (clz != null) {
	        	response = JsonUtil.jsonToBean(json, clz);
	        }
		} catch (Exception e) {
			e.printStackTrace();
		}
        return response;
	}
	
	
	public static String send (String actionUrl, String params, String method) {
		try {
			logger.debug(method + " method: request from " + actionUrl + " start...");
			if (params == null) params = "";
			URL url = new URL(actionUrl);
	        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
	        httpConn.setRequestProperty("Content-Length", String.valueOf(params.getBytes().length));
	        httpConn.setRequestProperty("Content-Type", "text/json; charset=UTF-8");
	        httpConn.setRequestMethod(method);
	        httpConn.setDoOutput(true);
	        httpConn.setDoInput(true);
	        OutputStream out = httpConn.getOutputStream();
	        out.write(params.getBytes("UTF-8"));
	        out.close();
	        params = new String(readInputStream(httpConn.getInputStream()), "UTF-8");
	        logger.debug(method + " method: request from " + actionUrl + " done...");
	        logger.debug("result: " + params);
	        System.out.println(params);
		} catch (Exception e) {
			params = null;
			e.printStackTrace();
		}
        return params;
	}
	
    /**
     * 从输入流中读取数据
     * @param inStream
     * @return
     * @throws Exception
     */
    private static byte[] readInputStream(InputStream inStream) throws Exception{
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while( (len = inStream.read(buffer)) !=-1 ){
            outStream.write(buffer, 0, len);
        }
        byte[] data = outStream.toByteArray();
        outStream.close();
        inStream.close();
        return data;
    }
}
